"use client";
import { useEffect, useState } from "react";

export default function ThemeToggle() {
  const [isDark, setIsDark] = useState(false);

  useEffect(() => {
    const stored = typeof window !== "undefined" ? localStorage.getItem("vh-theme") : null;
    const preferDark = window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
    const shouldDark = stored ? stored === "dark" : preferDark;
    setIsDark(shouldDark);
    document.documentElement.classList.toggle("dark", shouldDark);
  }, []);

  return (
    <button
      aria-label="切换主题"
      onClick={() => {
        const next = !isDark;
        setIsDark(next);
        document.documentElement.classList.toggle("dark", next);
        localStorage.setItem("vh-theme", next ? "dark" : "light");
      }}
      className="rounded-md border border-zinc-300 px-3 py-1.5 text-sm dark:border-zinc-700"
    >
      {isDark ? "浅色" : "深色"}
    </button>
  );
}


